﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using TracNghiem.Areas.Admin.Models;
using System.Collections;

namespace TracNghiem.Areas.Admin.Controllers
{
    public class TupleModelBinder : DefaultModelBinder
{
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
     {
        if (modelType == typeof(Tuple<Test_QuestionModel, List<Test_AnswerModel>>))
            return new Tuple<Test_QuestionModel, List<Test_AnswerModel>>(new Test_QuestionModel(), new List<Test_AnswerModel>());

        if (modelType == typeof(Tuple<TestModel, List<Test_DetailModel>>))
            return new Tuple<TestModel, List<Test_DetailModel>>(new TestModel(), new List<Test_DetailModel>());

        if (modelType == typeof(Tuple<TestModel, List<Test_QuestionModel>>))
            return new Tuple<TestModel, List<Test_QuestionModel>>(new TestModel(), new List<Test_QuestionModel>());

        return base.CreateModel(controllerContext, bindingContext, modelType);
        }
     }
    [Authorize(Roles = "admin")]
    public class Test_QuestionController : Controller
    {
        //
        // GET: /Admin/Test_Question/
        Test_QuestionModel Test_QuestionModel = new Test_QuestionModel();
        Test_AnswerModel Test_AnswerModel = new Test_AnswerModel();
        PhanLoaiModel PhanLoaiModel = new PhanLoaiModel();
        DichvuModel DichvuModel = new DichvuModel();
        public ActionResult Index(int id)
        {   
            List<Test_QuestionModel> ts = Test_QuestionModel.getTest_Question(id);
            List<PhanLoaiModel> PhanLoaiModel_ =  PhanLoaiModel.getPhan_LoaiByDV(id);
            ViewBag.phanloai_id = new SelectList(PhanLoaiModel_, "id", "name");
            DichvuModel DichvuModel_ = DichvuModel.getDichvu().Find(delegate(DichvuModel s) { return s.id == id.ToString(); });
            ViewBag.dichvu_id = DichvuModel_.id;
            ViewBag.ten_dich_vu = DichvuModel_.name;
            return View(ts);
        }

        public ActionResult DeleteTest_Question(int id,int dichvu_id)
        {
            if (Test_QuestionModel.checkSubItem(id) > 0)
            {
                TempData["error"] = "Không thể xóa câu hỏi do đã được sử dụng!";
                return RedirectToAction("Index", new { id = dichvu_id });
            }
            Test_QuestionModel.deleteTest_Question(id);
            List<Test_QuestionModel> ts = Test_QuestionModel.getTest_Question(id);
            TempData["msg"] = "Thông tin mới đã được cập nhật thành công!";
            return RedirectToAction("Index", new { id = dichvu_id  });
        }
        [HttpPost]
        public ActionResult CheckedAction(int[] Items)
        {
            string dichvu_id = Request.Form["dichvu_id"];
            foreach (int item in Items)
            {
                if (Test_QuestionModel.checkSubItem(item) > 0)
                {
                    TempData["error"] = "Không thể xóa câu hỏi do đã được sử dụng!";
                    return RedirectToAction("Index", new { id = dichvu_id });
                }
            }
            foreach (int item in Items)
            {
                Test_QuestionModel.deleteTest_Question(item);
            }
            TempData["msg"] = "Thông tin mới đã được cập nhật thành công!";
            return RedirectToAction("Index", new { id = dichvu_id });
        }
        public ActionResult AddTest_Question(int id)
        {
            List<PhanLoaiModel> PhanLoaiModel_ = PhanLoaiModel.getPhan_LoaiByDV(id);
            ViewBag.phanloai_id = new SelectList(PhanLoaiModel_, "id", "name");
            ViewBag.dichvu_id = id;
            DichvuModel DichvuModel_ = DichvuModel.getDichvu().Find(delegate(DichvuModel s) { return s.id == id.ToString(); });
            ViewBag.ten_dich_vu = DichvuModel_.name;
            return View(Test_QuestionModel);
        }
        [HttpPost]
        public ActionResult AddTest_Question(Test_QuestionModel Test_Question)
        {
            string dichvu_id = Request.Form["dichvu_id"];
            string[] cau_tra_loi = Request.Form.GetValues("cau_tra_loi");                   

            string cb_index = Request.Form["cb_index"];
            List<PhanLoaiModel> PhanLoaiModel_ = PhanLoaiModel.getPhan_LoaiByDV(Convert.ToInt32(dichvu_id));
            DichvuModel DichvuModel_ = DichvuModel.getDichvu().Find(delegate(DichvuModel s) { return s.id == dichvu_id.ToString(); });
            if (ModelState.IsValid)
            {
                if (Test_QuestionModel.checkExist(Test_Question) > 0)
                {
                    TempData["error"] = "Tên câu hỏi đã tồn tại!";
                    ViewBag.phanloai_id = new SelectList(PhanLoaiModel_, "id", "name");
                    ViewBag.ten_dich_vu = DichvuModel_.name;
                    ViewBag.dichvu_id = dichvu_id;
                    return View(Test_Question);
                }
                Test_Question.ngay_tao = DateTime.Now.ToString("dd/MM/yyyy");
                Test_Question.addTest_Question(Test_Question);                
                int status = 0;
                for (int i = 0; i < cau_tra_loi.Length; i++)
                {
                    if (cb_index == i.ToString())
                        status = 1;
                    else status = 0;
                    Test_Question.addTest_Answer(cau_tra_loi[i],status,i+1);
                }

                Test_SubjectModel Test_SubjectModel = new Test_SubjectModel();
                ViewBag.phanloai_id = new SelectList(PhanLoaiModel_, "id", "name");
                ViewBag.ten_dich_vu = DichvuModel_.name;
                ViewBag.dichvu_id = dichvu_id;
                TempData["msg"] = "Thông tin mới đã được cập nhật thành công!";
                return View(Test_Question);
            }
            TempData["error"] = "Bạn đã nhập sai thông tin!";
            ViewBag.phanloai_id = new SelectList(PhanLoaiModel_, "id", "name");
            ViewBag.ten_dich_vu = DichvuModel_.name;
            ViewBag.dichvu_id = dichvu_id;
            return View(Test_Question);
        }
        //public ActionResult FindTest_Question()
        //{
        //    return RedirectToAction("Index");
        //}
        public ActionResult EditTest_Question(int dichvu_id,int id)
        {
            Test_QuestionModel Test_QuestionModel_ = Test_QuestionModel.getTest_Question(dichvu_id).Find(delegate(Test_QuestionModel s) { return s.id == id.ToString(); });

            DichvuModel DichvuModel_ = DichvuModel.getDichvu().Find(delegate(DichvuModel s) { return s.id == dichvu_id.ToString(); });
            ViewBag.dichvu_id = dichvu_id;
            ViewBag.ten_dich_vu = DichvuModel_.name;

            ViewBag.cau_hoi_id = Test_QuestionModel_.id;
            List<Test_AnswerModel> Test_Answer_ = Test_AnswerModel.getTest_AnswerByCauHoi(Test_QuestionModel_.id);

            List<PhanLoaiModel> PhanLoaiModel_ = PhanLoaiModel.getPhan_LoaiByDV(dichvu_id);
            
            List<SelectListItem> dropdownlist1 = new List<SelectListItem>();
            foreach(var item in PhanLoaiModel_)
            {
                if(item.id==Test_QuestionModel_.phanloai_id)
                    dropdownlist1.Add(new SelectListItem { Text = item.name, Value = item.id, Selected = true });
                else
                    dropdownlist1.Add(new SelectListItem { Text = item.name, Value = item.id });                
            }
            ViewBag.option_id = dropdownlist1;
            //Test_QuestionModel_.option_id = new SelectList(PhanLoaiModel_, "id", "name");
            
            return View(Tuple.Create(Test_QuestionModel_, Test_Answer_));
        }
        [HttpPost]
        public ActionResult EditTest_Question(Tuple<Test_QuestionModel, List<Test_AnswerModel>> t)
        {
            List<PhanLoaiModel> PhanLoaiModel_ = PhanLoaiModel.getPhan_Loai();
            string cau_hoi_id = Request.Form["cauhoi_id"];
            string dichvu_id = Request.Form["dichvu_id"];
            if (ModelState.IsValid)
            {
                t.Item1.status = Request["status"];
                t.Item1.phanloai_id = Request["phanloai_id"];                
                Test_QuestionModel.updateTest_Question(t.Item1);
                ViewBag.phanloai_id = new SelectList(PhanLoaiModel_, "id", "name");
                
                string id_array = Request.Form["cau_tl_hidden"];
                if (Test_AnswerModel.checkSubItem(id_array, cau_hoi_id) > 0)
                {
                    TempData["error"] = "Không thể xóa câu trả lời này do đã được sử dụng!";
                    return RedirectToAction("EditTest_Question", new { dichvu_id = dichvu_id, id = cau_hoi_id });
                }
                Test_AnswerModel.EditTest_Answer_Delete(id_array, cau_hoi_id);

                string[] id_array_split = id_array.Split(',');
                string[] cau_tra_loi = Request.Form.GetValues("cau_tra_loi");
                string cb_index = Request.Form["cb_index"];
                string status="0";
                for (int i = 0; i < cau_tra_loi.Length; i++)
                {
                    if (cb_index == i.ToString())
                        status = "1";
                    else status = "0";
                    if (i < id_array_split.Length)
                        Test_AnswerModel.EditTest_AnswerEdit(id_array_split[i], cau_tra_loi[i], status);
                    else
                        Test_AnswerModel.EditTest_AnswerAdd(cau_tra_loi[i], status, cau_hoi_id);
                }
                TempData["msg"] = "Thông tin mới đã được cập nhật thành công!";

                return RedirectToAction("EditTest_Question", new { dichvu_id = dichvu_id, id = cau_hoi_id });
            }
            TempData["error"] = "Bạn đã nhập sai thông tin!";
            ViewBag.phanloai_id = new SelectList(PhanLoaiModel_, "id", "name");
            ViewBag.dichvu_id = Request.Form["dichvu_id"];

            //Test_SubjectModel Test_SubjectModel = new Test_SubjectModel();
            //List<Test_SubjectModel> test_SubjectModel = Test_SubjectModel.getTest_SubjectById(Convert.ToInt32(ViewBag.chu_de_id));
            //ViewBag.ten_chu_de = test_SubjectModel[0].name;

            //List<Test_AnswerModel> Test_Answer_ = Test_AnswerModel.getTest_AnswerByCauHoi(t.Item1.id);

            return RedirectToAction("EditTest_Question", new { dichvu_id = dichvu_id, id = cau_hoi_id });
        }
        [HttpPost]
        public ActionResult FindTest_Question(string timkiem)
        {            
            int id = Convert.ToInt32(Request.Form["dichvu_id"]);
            string phanloai_id = "";
            int num;
            string s = "";
            //add by Namtd 09/03/2014
            ViewBag.selectedPhanloai = "";
            if (int.TryParse(Request.Form["option_id"], out num))
            {
                phanloai_id = Request.Form["option_id"];
                s = " b.id=" + phanloai_id + " AND ";
                ViewBag.selectedPhanloai = Request.Form["option_id"];
            }
            string sql;
            string dk = "";
            if (Request["select_option"] == "cau_hoi.name")
                dk = "a.name";
            //else if (Request["select_option"] == "stations.name")
            //    dk = "b.name";
            //else if (Request["select_option"] == "main_stations.name")
            //    dk = "d.name";            
            if (timkiem == "")
                sql = s + dk + " like '%" + timkiem + "%' or " + dk + " is null";
            else
                sql = s + "(" + dk + " like '%" + timkiem + "%' or upper(" + dk + ") like upper('%" + timkiem + "%'))";

            ViewBag.find_textbox = timkiem;
            ViewBag.find_selectbox = Request["select_option"];
            Test_QuestionModel Test_QuestionModel = new Test_QuestionModel();
            List<Test_QuestionModel> Test_Question = Test_QuestionModel.FindTest_Question(id,sql);
            List<PhanLoaiModel> PhanLoaiModel_ = PhanLoaiModel.getPhan_LoaiByDV(id);
            if (ViewBag.selectedPhanloai.Length == 0)
                ViewBag.phanloai_id = new SelectList(PhanLoaiModel_, "id", "name");
            else
            {
                ViewBag.phanloai_id = new SelectList(PhanLoaiModel_, "id", "name", ViewBag.selectedPhanloai);
            }

            DichvuModel DichvuModel_ = DichvuModel.getDichvu().Find(delegate(DichvuModel dv) { return dv.id == id.ToString(); });
            ViewBag.dichvu_id = id;
            ViewBag.ten_dich_vu = DichvuModel_.name;            
            return View("Index", Test_Question);
        }
    }
}
